package ${tempValues.package_this_file};

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class KafkaProducerConfig {

    // common
<#if kafka?? && kafka.bootstrapServers??>
    @Value("${kafka.bootstrapServers}")
    private String bootstrapServers;
<#else >
    @Value("${r'${bootstrap.servers}'}")
    private String bootstrapServers;
</#if>

    // producer
    @Value("${r'${retries:3}'}")
    private Integer retries;
    @Value("${r'${batch.size:16384}'}")
    private Integer batchSize;
    @Value("${r'${linger.ms:2}'}")
    private Integer lingerMs;
    @Value("${r'${buffer.memory:33554432}'}")
    private Integer bufferMemory;
    @Value("${r'${key.serializer:org.apache.kafka.common.serialization.StringSerializer}'}")
    private String keySerializer;
    @Value("${r'${value.serializer:org.apache.kafka.common.serialization.StringSerializer}'}")
    private String valueSerializer;

    @Bean
    public DefaultKafkaProducerFactory kafkaProducerFactory() {
        Map<String, Object> configs = new HashMap<>();
        configs.put("bootstrap.servers", bootstrapServers);
        configs.put("retries", retries);
        configs.put("batch.size", batchSize);
        configs.put("linger.ms", lingerMs);
        configs.put("buffer.memory.ms", bufferMemory);
        configs.put("key.serializer", keySerializer);
        configs.put("value.serializer", valueSerializer);

        DefaultKafkaProducerFactory defaultKafkaProducerFactory = new DefaultKafkaProducerFactory(configs);
        return defaultKafkaProducerFactory;
    }

    @Bean
    public KafkaTemplate kafkaTemplate(DefaultKafkaProducerFactory kafkaProducerFactory) {
        KafkaTemplate kafkaTemplate = new KafkaTemplate<>(kafkaProducerFactory, true);
        return kafkaTemplate;
    }

}
